import  AuthAPI  from "@/api/auth";
import UserAPI from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/model";
import { UserInfo } from "@/api/user/model";
import { TOKEN_KEY } from "@/enums/CacheEnum";

export const useUserStore = defineStore("user",()=>{
    const user = ref<UserInfo>({
        roles:[], // 角色
        perms:[], // 权限
    })
    
    /**
     * 登录调用
     * @param LoginData 登录参数
     * @returns 登录结果
     */

    function login(loginData: LoginData) {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.login(loginData).then(response => {
                const { tokenType, accessToken } = response.data;
                localStorage.setItem(TOKEN_KEY, `${tokenType} ${accessToken}`);
                resolve();
            }).catch(error => {
                reject(error);
            })
        })
    }

    // 获取用户信息（昵称，头像，角色集合，权限集合）
    function getUserInfo() {
        return new Promise<UserInfo>((resolve, reject) => {
            UserAPI.getInfo().then((data) => {
                if(!data) {
                    reject(new Error('获取用户信息失败, 请从新登录'));
                    return;
                }
                if(!data.roles || data.roles.length <= 0) {
                    reject(new Error('角色集合必须是一个非空的数组'));
                    return;
                }
                Object.assign(user.value, {...data});
                resolve(data);
            })
            .catch(error => {
                reject(error);
            })
        })
    }

    // 登出
    function logout() {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.logout().then(() => {
                localStorage.removeItem(TOKEN_KEY);
                // resetRouter();
                location.reload(); // 清空路由
                resolve();
            }).catch(error => {
                reject(error);
            })
        })
    }

    // remove token
    function resetToken() {
        return new Promise<void>((resolve, reject) => {
            // localStorage.removeItem(TOKEN_KEY);
            localStorage.setItem(TOKEN_KEY, '');
            resetRouter();
            resolve();
        })
    }

    return {
        user,
        login,
        getUserInfo,
        logout,
        resetToken
    }
})

export function useUserStoreHook() {
    return useUserStore(store);
}

